package com.handy.util;

import cn.hutool.core.util.StrUtil;
import com.handy.constants.BaseConstants;

import javax.servlet.http.HttpServletRequest;

/**
 * @author handy
 */
public class IpUtil {

    /**
     * 获取ip
     *
     * @param req 请求
     * @return ip
     */
    public static String getIp(HttpServletRequest req) {
        String xip = req.getHeader("X-Real-IP");
        String xFor = req.getHeader("X-Forwarded-For");
        if (StrUtil.isNotEmpty(xFor) && !BaseConstants.UNKNOWN.equalsIgnoreCase(xFor)) {
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = xFor.indexOf(",");
            if (index != -1) {
                return xFor.substring(0, index);
            } else {
                return xFor;
            }
        }
        xFor = xip;
        if (StrUtil.isNotEmpty(xFor) && !BaseConstants.UNKNOWN.equalsIgnoreCase(xFor)) {
            return xFor;
        }
        if (StrUtil.isBlank(xFor) || BaseConstants.UNKNOWN.equalsIgnoreCase(xFor)) {
            xFor = req.getHeader("Proxy-Client-IP");
        }
        if (StrUtil.isBlank(xFor) || BaseConstants.UNKNOWN.equalsIgnoreCase(xFor)) {
            xFor = req.getHeader("WL-Proxy-Client-IP");
        }
        if (StrUtil.isBlank(xFor) || BaseConstants.UNKNOWN.equalsIgnoreCase(xFor)) {
            xFor = req.getHeader("HTTP_CLIENT_IP");
        }
        if (StrUtil.isBlank(xFor) || BaseConstants.UNKNOWN.equalsIgnoreCase(xFor)) {
            xFor = req.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (StrUtil.isBlank(xFor) || BaseConstants.UNKNOWN.equalsIgnoreCase(xFor)) {
            xFor = req.getRemoteAddr();
        }
        //ip地址最长50
        if (xFor != null && xFor.length() > 50) {
            xFor = xFor.substring(0, 50);
        }
        return xFor;
    }

}
